package com.flyxiaozhu.erp.service.controllers;

import com.flyxiaozhu.erp.core.entities.Goods;
import com.flyxiaozhu.erp.core.libs.ErrorCode;
import com.flyxiaozhu.erp.core.libs.JSONResult;
import com.flyxiaozhu.erp.core.repositories.GoodsRepository;
import com.flyxiaozhu.erp.core.repositories.GoodsSkuRepository;
import com.flyxiaozhu.erp.core.repositories.GoodsStockLogRepository;
import com.flyxiaozhu.erp.core.repositories.GoodsTagRepository;
import com.flyxiaozhu.erp.core.services.GoodsCategoryService;
import com.flyxiaozhu.erp.core.services.GoodsService;
import com.flyxiaozhu.erp.core.utils.CollectionUtils;
import com.flyxiaozhu.erp.service.resps.GoodsResp;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Set;

/**
 * @author flyxiaozhu
 * @date 2019-04-26 11:42
 */
@RestController
@Validated
public class GoodsController {
    @Autowired
    GoodsService goodsService;
    @Autowired
    GoodsCategoryService goodsCategoryService;
    @Autowired
    GoodsTagRepository goodsTagRepository;
    @Autowired
    GoodsRepository goodsRepository;
    @Autowired
    GoodsStockLogRepository goodsStockLogRepository;
    @Autowired
    GoodsSkuRepository goodsSkuRepository;

    /**
     * 商品分类列表
     *
     * @return
     */
    @RequestMapping(value = "/goods/categories")
    public JSONResult getCategories() {
        return new JSONResult().put("categories", goodsCategoryService.getTree());
    }

    /**
     * 商品列表
     *
     * @param pageable
     * @return
     */
    @RequestMapping(value = "/goods/list")
    public JSONResult getGoodsList(@RequestParam(defaultValue = "") String keyword,
                                   @RequestParam(defaultValue = "0") long categoryId,
                                   @RequestParam(defaultValue = "") String tagIds,
                                   @RequestParam(defaultValue = "-99") Long minPrice,
                                   @RequestParam(defaultValue = "-99") Long maxPrice,
                                   @RequestParam(defaultValue = "-99") Long minStock,
                                   @RequestParam(defaultValue = "-99") Long maxStock,
                                   @PageableDefault Pageable pageable) {
        Set<Long> categoryIds = null;
        if (categoryId != 0) {
            categoryIds = goodsCategoryService.getChildrenIds(goodsCategoryService.getTree(), categoryId);
            if (categoryIds == null) {
                return new JSONResult(ErrorCode.NO_DATA, "分类ID错误");
            }
            categoryIds.add(categoryId);
        }

        List<Long> tagIdsL = null;
        if (StringUtils.isNotBlank(tagIds)) {
            tagIdsL = CollectionUtils.parseSplitStr(tagIds, ",", Long::valueOf);
        }

        Page<Goods> list = goodsService.getList(keyword, categoryIds, tagIdsL, minPrice, maxPrice, minStock, maxStock, pageable);

        List<GoodsResp> resps = CollectionUtils.map(list.getContent(), GoodsResp::new);
        return new JSONResult(list, pageable.getPageNumber())
                .put("list", resps);
    }

    /**
     * 商品库存
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/goods/stocks")
    public JSONResult getStocks(@NotBlank(message = "ids 不能为空") String ids) {
        List<Long> goodsIds = CollectionUtils.parseSplitStr(ids, ",", Long::valueOf);
        List<Goods> goods = goodsRepository.findByIdIn(goodsIds);

        return new JSONResult().put("stocks", CollectionUtils.columnMapFull(goods, new CollectionUtils.ColumnMapFilter2<Goods, Long, Integer>() {
            @Override
            public Long getKey(Goods o) {
                return o.getId();
            }

            @Override
            public Integer getValue(Goods o) {
                return o.getStock();
            }
        }));
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/goods/detail")
    public JSONResult getGoodsInfo(@NotNull @Min(1) Long id) {
        //基础数据拿缓存
        Goods goods = goodsService.findById(id);
        if (goods == null) {
            return new JSONResult(ErrorCode.NO_DATA, "商品ID错误");
        }

//        //库存数据实时 商品使用了redis缓存，这需要次步骤
//        goods.setStock(goodsRepository.getStock(goods.getId()));
//        if (goods.getGoodsSkus() != null && goods.getGoodsSkus().size() > 0) {
//            List<Object> skuStocks = goodsSkuRepository.getStockByGoodsId(goods.getId());
//
//            Map<Long, Integer> stockMap = CollectionUtils.columnMapFull(skuStocks, new CollectionUtils.ColumnMapFilter2<Object, Long, Integer>() {
//                @Override
//                public Long getKey(Object o) {
//                    return Long.valueOf(String.valueOf(((Object[]) o)[0]));
//                }
//
//                @Override
//                public Integer getValue(Object o) {
//                    return Integer.valueOf(String.valueOf(((Object[]) o)[1]));
//                }
//            });
//
//            for (GoodsSku sku : goods.getGoodsSkus()) {
//                sku.setStock(stockMap.getOrDefault(sku.getId(), 0));
//            }
//        }

        GoodsResp goodsResp = new GoodsResp(goods);
        return new JSONResult().put("goods", goodsResp);
    }
}
